package org.genntii.smuserserver.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.genntii.smcommon.constant.GatewayConstant;
import org.genntii.smcommon.result.PageResult;
import org.genntii.smcommon.result.Result;
import org.genntii.smdomain.doc.VO.UserDocVO;
import org.genntii.smdomain.dto.EmailRegUserDTO;
import org.genntii.smdomain.dto.UserDTO;
import org.genntii.smdomain.dto.UserDirectoryDTO;
import org.genntii.smdomain.dto.UserUpdateDTO;
import org.genntii.smdomain.entity.RegEmail;
import org.genntii.smdomain.entity.User;
import org.genntii.smdomain.vo.ArticleVO;
import org.genntii.smdomain.vo.CommentVO;
import org.genntii.smdomain.vo.UserVO;

import org.genntii.smuserserver.client.UserDirectoryClient;
import org.genntii.smuserserver.domain.LoginDTO;
import org.genntii.smuserserver.mapper.UserMapper;
import org.genntii.smuserserver.service.CacheService;
import org.genntii.smuserserver.service.LoginService;
import org.genntii.smuserserver.service.RegisterService;
import org.genntii.smuserserver.service.UserService;
import org.genntii.smuserserver.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Tag(name = "用户服务接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RegisterService registerService;

    @Resource
    private LoginService loginService;

    @Resource
    private CacheService cacheService;

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDirectoryClient userDirectoryClient;

    @Operation(summary = "userDocVO")
    @GetMapping("userdoc")
    public Result<UserDocVO> getUserDocVOById(@RequestParam("userId")Long userId){
        return Result.success(userService.getUserDocVOById(userId));
    }

    @GetMapping("userExists")
    @Operation(summary = "获取用户是否存在")
    public Result<Boolean> userExists(@RequestParam("username") String username) {
        return Result.success(userService.userExists(username));
    }

    @GetMapping("/{userId}")
    Result<UserVO> getUserById(@PathVariable Long userId){
        return Result.success(userService.getUserById(userId));
    }

    @GetMapping("/dc/{targetId}")
    Result<UserVO> getUserById(@PathVariable Long targetId,
                               HttpServletRequest request){
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(userService.dcGetUserById(targetId,userId));
    }

    @GetMapping
    public Result<Map<Long, UserVO>> getUserListMapByIds(@RequestParam("userIds") ArrayList<Long> userIds){
        return Result.success(userService.getUserListMapByIds(userIds));
    }

    @GetMapping("/exists/{userId}")
    public Result<Boolean> userIdExists(@PathVariable Long userId){
        return Result.success(userMapper.userIdExists(userId) == 1);
    }

    @PostMapping("/sendEmail")
    @Operation(summary = "发送验证码")
    public Result<String> sendEmail(@RequestBody RegEmail email){
        if (registerService.emailExists(email.getEmail())){
            return Result.error("该邮箱已被使用");
        }

        int cap = cacheService.captchaCache(email.getEmail());

        String html = "<div>"+cap+"</div>";
        //TODO 写一个邮箱html模板

        registerService.sendHtmlMail(email.getEmail(),"感谢宁的注册",html);

        return Result.success("发送成功");
    }

    @PostMapping("/register")
    @Operation(summary = "邮箱注册")
    public Result<String> register(@RequestBody EmailRegUserDTO userDTO){

        try {
            redisTemplate.opsForValue().get(userDTO.getEmail());
        }catch (Exception e){
            return Result.error("验证码错误或失效");
        }

        if (registerService.usernameExists(userDTO.getUsername())){
            return Result.error("用户名已被使用");
        }

        User userReg =new User();
        String salt = BCrypt.gensalt();
        userReg.setSalt(salt);
        userReg.setUsername(userDTO.getUsername());
        userReg.setPassword(BCrypt.hashpw(userDTO.getPassword(),salt));
        userReg.setEmail(userDTO.getEmail());

        String topic = "注册成功!";
        String message = "<div>尊敬的"+userReg.getUsername()+"</div>"+"<div>您已成功注册</div>";

        registerService.save(userReg);

        userDirectoryClient.addDefaultFavorite(new UserDirectoryDTO(userReg.getId(),"默认文件夹",null,(byte) 0),userReg.getId());

        registerService.sendHtmlMail(userReg.getEmail(),topic,message);

        return Result.success("注册成功");

    }

    @PostMapping("login")
    @Operation(summary = "通过用户名登录")
    public Result<UserVO> login(@RequestBody LoginDTO loginDTO, HttpServletRequest request){
        String ipv4 = IpUtil.getIpAddr(request);
        String client =  request.getHeader("Client-Name");
        return Result.success(loginService.login(loginDTO, client, ipv4));

    }

    @GetMapping("openId")
    @Operation(summary = "绑定steamOpenId")
    Result openId(@RequestParam("steamId") Long steamId, @RequestParam("userId")Long userId){
        userService.insertSteamId(steamId,userId);
        return Result.success();
    }

    @GetMapping("steamIdExists")
    public Result steamIdExists(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String clientType = request.getHeader("Client-Name");
        if (userService.steamIdExists(token,clientType)){
            return Result.success();
        }
        return Result.error("未绑定steamId");

    }
    @Operation(summary = "修改用户信息")
    @PutMapping("/update")
    public Result backgroundImageModify(@RequestBody UserDTO userDTO){
        userService.updateUser(userDTO);
        return Result.success();
    }

    @Operation(summary = "根据用户id查找文章")
    @GetMapping("/article")
    public Result<PageResult<ArticleVO>> getArticle(@RequestParam Integer pageNum,
                                                          @RequestParam Integer pageSize,
                                                          @RequestParam Long userId){
//        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(userService.getArticle(pageSize,pageNum,userId));
    }

    @Operation(summary = "根据用户id查找评论")
    @GetMapping("comment")
    public Result<PageResult<CommentVO>> getComment(@RequestParam Integer pageNum,
                                         @RequestParam Integer pageSize,
                                         @RequestParam Long userId) {
//        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(userService.getComment(pageSize,pageNum,userId));
    }

    @Operation(summary = "根据用户id更新用户信息")
    @PutMapping
    public Result<UserVO> userUpdate(@RequestBody UserUpdateDTO userUpdateDTO, HttpServletRequest request){
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(userService.updateUserMessage(userUpdateDTO,userId));
    }

//    @Operation(summary = "用户关注粉丝数更新")
//    @GetMapping("/updateFollower")
//    public Result updateFollowerSubscriber(@RequestParam("follower")Long followerNum,
//                                           @RequestParam("subscriber")Long subscriberNum){
//        return
//    }

    @GetMapping("/test")
    public Result<LocalDateTime> timeTest(){
        return Result.success(LocalDateTime.now());
    }

}
